package com.jnr.huatu.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * 画图
 * @author：景辉
 * created at 2017/2/8 0008 上午 9:29
 */

public class MyView extends View {

    private Bitmap mBitmap;
    private Canvas mCanvas;
    private Path mPath;
    private Paint mPaint;
    private int mLastX;
    private int mLastY;

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        //记录用户绘制的path
        mPath = new Path();
        //绘制画笔
        mPaint = new Paint();
        mPaint.setColor(Color.GREEN);//初始化画笔颜色
        mPaint.setAntiAlias(true);//防止边缘锯齿
        mPaint.setDither(true);//设置防抖动
        mPaint.setStyle(Paint.Style.STROKE);//设置画笔为空心
        mPaint.setStrokeJoin(Paint.Join.ROUND);//设置画笔痕迹为圆
        mPaint.setStrokeCap(Paint.Cap.ROUND);//设置拐弯处为圆角
        mPaint.setStrokeWidth(20);//设置画笔宽度
    }

    /**
     * onMeasure设置视图大小的方法
     * @author：景辉
     * created at 2017/2/8 0008 上午 9:45
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getMeasuredWidth();//得到宽度
        int height = getMeasuredHeight();//得到高度
        //生成指定宽高的bitmap为32位
        mBitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mBitmap);//创建画布
    }

    /**
     * onDraw创建绘画方法，在这里面绘图
     * @author：景辉
     * created at 2017/2/8 0008 上午 10:01
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawPath();//绘制线条
        //新建一个画布，第一个参数导入已有的图，二三是初始的xy轴，四是画笔没有为空
        canvas.drawBitmap(mBitmap,0,0,null);
    }

    private void drawPath() {
        mCanvas.drawPath(mPath,mPaint);
    }

    /**
     * 触屏事件
     * @author：景辉
     * created at 2017/2/8 0008 上午 10:09
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();//获得行为
        int x = (int) event.getX();//获得触摸x位置
        int y = (int) event.getY();//获得触摸y位置
        switch (action){
            case MotionEvent.ACTION_DOWN://屏幕按下
                mLastX = x;//按下初始x轴
                mLastY = y;//按下初始y轴
                mPath.moveTo(mLastX,mLastY);//移动path
                break;
            case MotionEvent.ACTION_MOVE://屏幕拖动
                int dx = Math.abs(x - mLastX);
                int dy = Math.abs(y - mLastY);
                if (dx>3||dy>3){
                    mPath.lineTo(x,y);
                }
                mLastX = x;
                mLastY = y;
                break;
        }
        invalidate();
        return true;
    }
}
